<template>
	<view class="content" @click="handleClickOutside">
		<custom-bar :isShowBack="false">
			<view class="head" @click.stop="goManager">
				<image src="@/static/logo.png" mode="" style="width: 45rpx; height: 45rpx; padding-right: 20rpx">
				</image>
				<up-icon name="arrow-left-double" color="#0328fe" style="padding-right: 10rpx" size="20"
					v-if="pageIndex == 1 && identity"></up-icon>
				<text v-if="pageIndex == 1">{{
          itemTitle || userStore.getItemName() || "鑫暖云"
        }}</text>

				<text v-else>鑫暖云</text>
			</view>
		</custom-bar>
		<view class="main-action" v-if="pageIndex == 1">
			<up-search placeholder="搜索设备名称或ID" v-model="searchValue" @clickIcon="onSearch" @search="onSearch"
				@clear="onClear" :showAction="false" borderColor="#d7d7d7" bgColor="#fff"></up-search>
			<custom-select :options="cateList" v-model="selectedId" @scanTrue="handleScanTrue"
				@change="handleSelectChange" :setSearch="setSearch"></custom-select>
		</view>
		<view class="main-content" v-if="pageIndex == 1">
			<device-component ref="childRef" :itemId="itemId"></device-component>
		</view>
		<!-- 没做样式 先展示一下 -->
		<view class="main-content" v-else>
			<view class="manager-list" :iconSize="180" v-for="(item, i) in itemList" :key="i"
				@click="handleItemClick(item)">
				<view class="manager-list-left">
					<view class="manager-list-left-top">
						{{ item.itemName }}
					</view>
					<view class="manager-list-left-btm">
						设备:<text style="padding-left: 15rpx">{{ item.devCount }}台</text><text
							style="padding-left: 10rpx">在线{{ item.devOnlineCount }}台</text>
					</view>
				</view>
				<view class="manager-list-right">
					<up-icon name="arrow-right" size="40rpx"></up-icon>
				</view>
			</view>
			<view class="device-list-empty" v-if="emptyShow">
				<!-- <view class=""> 您还没有绑定项目 </view> -->
				<image src="@/static/empty.png" mode="" style="width: 250rpx; height: 250rpx"></image>
				<up-button type="primary" shape="circle" text="切换普通用户身份" style="width: 350rpx;"
					:loading="indntityLoading" @click="changeIdentity"></up-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		nextTick
	} from "vue";
	import {
		onLoad,
		onPullDownRefresh,
		onShow,
		onHide,
		onUnload,
	} from "@dcloudio/uni-app";
	import DeviceComponent from "../../components/device-component/device-component.vue";
	import {
		dictDataStore,
		dictKeys
	} from "@/store/dict.js";
	import {
		useUserStore
	} from "@/store/user";

	const dict = dictDataStore();
	const userStore = useUserStore();
	const pageIndex = ref(1);
	const selectedId = ref("");
	const childRef = ref();
	const itemList = ref([]);
	const searchValue = ref("");
	const setSearch = ref("");
	const itemTitle = ref("");
	const emptyShow = ref(false);
	const identity = ref('')
	const indntityLoading = ref(false)


	onLoad((e) => {
		// 交流版风速 sys_fan_speed
		dictKeys.forEach((key) => {
			let dicts = uni.getStorageSync(key);
			//本地没有 去查询
			if (!dicts.length) {
				uni.$u.http
					.post("/wechat/getDataByDicType", {
						dictType: key,
					})
					.then((res) => {
						//字典也不是很重要 先不用pinia存了
						uni.setStorageSync(key, res.data);
					});
			}
		});
		// 用户信息
		let openid = uni.getStorageSync("openid");
		if (openid) {
			// 查看是否有项目管理员权限
			uni.$u.http
				.post("/wechat/getUserInfo", {
					openid: openid,
				})
				.then((res) => {
					if (res.success) {
						userStore.setUserInfo(res)
					}
				});
		}

	});
	const stopAutoRefresh = () => {
		childRef.value.stopAutoRefresh();
	};

	onShow(() => {

		uni.$on("changePage", (data, user) => {
			if (data.from === "changeIdentify") {
				if (childRef.value) {
					// 清空设备列表
					childRef.value.deviceList = [];
				}
			}
			if (user == 'normal') {
				itemTitle.value = ''
				userStore.setItemName('')
			}
		});
		searchValue.value = "";
		init()

	});

	const init = () => {
		identity.value = uni.getStorageSync("identity");
		setTimeout(() => {
			if (!identity.value) {
				// uni.showLoading()
				pageIndex.value = 1;
				itemTitle.value = "";
				const reloadDeviceList = () => {
					if (
						childRef.value &&
						typeof childRef.value.onPullDownReload === "function"
					) {
						childRef.value.onPullDownReload();
					} else {
						// 如果组件还未加载完成，稍后再试
						setTimeout(reloadDeviceList, 100);
					}
				};
				setTimeout(() => {
					reloadDeviceList();
				}, 200);
			} else {
				// 管理员逻辑
				if (userStore.getItemName()) {
					// uni.showLoading()
					const reloadDeviceList = () => {
						if (
							childRef.value &&
							typeof childRef.value.onPullDownReload === "function"
						) {
							childRef.value.onPullDownReload();
						} else {
							// 如果组件还未加载完成，稍后再试
							setTimeout(reloadDeviceList, 200);
						}
					};
					nextTick(reloadDeviceList);
				} else {
					pageIndex.value = 2;
					getItemList();
					if (
						childRef.value &&
						typeof childRef.value.stopAutoRefresh === "function"
					) {
						childRef.value.stopAutoRefresh();
					}
				}
			}
		}, 150);
	}
	onPullDownRefresh(() => {
		childRef.value.onPullDownReload();
	});
	const itemId = ref("");
	// 扫码结果
	const scanResult = ref("");
	// 响应式数据
	const cateList = ref([{
			id: "1",
			name: "添加设备",
		},
		{
			id: "2",
			name: "扫一扫",
		},
	]);

	// 处理扫码成功事件
	const handleScanTrue = (result) => {
		console.log("父组件接收到扫码结果:", result);
		scanResult.value = result;

		// 可以在这里添加其他处理逻辑
		// 例如：发送结果到服务器、更新本地数据等
	};
	// 处理下拉选择变化
	const handleSelectChange = (option) => {
		console.log("选择项变化:", option);
	};
	const handleClickOutside = () => {
		if (childRef.value && typeof childRef.value.onContainerClick === "function") {
			childRef.value.onContainerClick();
		}
	};
	const getItemList = () => {
		// uni.showLoading()
		let data = {
			//应该没有那么多组织,先没做分页
			pageNum: 1,
			pageSize: 99,
		};
		uni.$u.http.post("/wechat/getItemListByOpenid", data).then((res) => {
			// res.data.push({
			// 	itemName: '模拟机构1',
			// 	itemId: 2,
			// 	devCount: 10,
			// 	devOnlineCount: 1
			// })
			itemList.value = res.data;
			if (itemList.value.length) {
				emptyShow.value = false;
			} else {
				emptyShow.value = true;
			}
		});
	};
	const handleItemClick = (data) => {
		userStore.setItemId(data.itemId);
		userStore.setItemName(data.itemName);
		itemTitle.value = data.itemName;
		//转到原来页面
		pageIndex.value = 1;
		setTimeout(() => {
			childRef.value.onPullDownReload();
		}, 500);
	};
	const onSearch = () => {
		if (childRef.value && typeof childRef.value.handleSearch === "function") {
			childRef.value.handleSearch(searchValue.value);
		}
	};

	const onClear = () => {
		searchValue.value = "";
		if (childRef.value && typeof childRef.value.handleSearch === "function") {
			childRef.value.handleSearch("");
		}
	};
	const goManager = () => {
		if (
			(pageIndex.value == 2 && !userStore.getUserInfo().isAdmin) ||
			!uni.getStorageSync("identity")
		) {
			return;
		} else {
			pageIndex.value = 2;
			// 如果 childRef 存在且有停止自动刷新的方法，调用它
			if (
				childRef.value &&
				typeof childRef.value.stopAutoRefresh === "function"
			) {
				childRef.value.stopAutoRefresh();
			}
			getItemList();
		}
	};

	const changeIdentity = () => {
		indntityLoading.value = true
		uni.setStorageSync('identity', false)
		userStore.setItemName(null);
		userStore.setItemId(null);
		pageIndex.value = 1;
		init()
		indntityLoading.value = false
	}
	onHide(() => {
		itemList.value = [];
		if (childRef.value && typeof childRef.value.stopAutoRefresh === "function") {
			childRef.value.stopAutoRefresh();
		}
	});
</script>

<style scoped lang="scss">
	@import "./index.scss";

	.content {
		width: 100vw;
		min-height: 100vh;
		background: linear-gradient(to bottom, #dae0eb, #f1f1f1);
	}

	/* 隐藏原生下拉箭头 */
	.main-action :deep(.up-select__prefix) {
		display: none !important;
	}

	.main-action :deep(.u-select__content .u-select__options) {
		margin-top: 30rpx;
		width: auto;
	}

	.main-action :deep(.u-select__content .u-select__options .u-select__options_item) {
		padding: 8rpx 12rpx;
	}

	.main-content :deep(.u-select__label) {
		background: #fff;
		width: 200rpx;
		height: 28px;
		line-height: 28px;
		padding: 0 20rpx;
		overflow: hidden;
	}

	.main-content :deep(.u-select__content .u-select__options__wrap) {
		position: absolute;
		top: 29px;
		left: 0px;
		margin-bottom: 0;
	}

	.main-content :deep(.u-select__content .u-select__options) {
		margin-top: 0;
		width: 240rpx !important;
		max-height: 300rpx;
	}

	.main-content :deep(.u-select__content .u-select__options .u-select__options_item) {
		border-bottom: 1px solid #e1e1e1;
		padding: 0 20rpx;
		font-size: 26rpx;
	}

	.project-list-container {
		background-color: #f5f5f5;
		padding: 10px;
	}

	.project-item {
		background-color: #fff;
		margin-bottom: 10px;
		padding: 15px;
		border-radius: 4px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		cursor: pointer;
		transition: background-color 0.2s ease;
	}

	.project-item:hover {
		background-color: #fafafa;
	}

	.project-title {
		font-size: 16px;
		font-weight: 500;
		margin-bottom: 4px;
	}

	.project-info {
		font-size: 14px;
		color: #999;
	}

	.manager-list {
		height: 130rpx;
		margin: 25rpx 40rpx;
		background: #fff;
		border-radius: 10px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 40rpx;

		.manager-list-left-top {
			line-height: 50rpx;
			margin-bottom: 10rpx;
		}

		.manager-list-left-btm {
			color: #797979;
			font-size: 26rpx;
		}
	}

	.itemLabel {
		width: 100%;
		display: flex;
		justify-content: center;
	}
</style>